package com.geezdata.cps.base.aop;

import java.io.Serializable;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.geezdata.cps.base.constant.Constants;
import com.geezdata.cps.base.request.BaseRequest;


@Aspect
@Order(2)
@Component
public class InjectLogIdAspect {
    @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object validate(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] arguments = joinPoint.getArgs();
        if (arguments != null) {
            for (Object argument : arguments) {
                if (argument instanceof BaseRequest) {
                	SecurityManager sm = ThreadContext.getSecurityManager();
                	if(sm == null ) {
                		return joinPoint.proceed();
                	}
                	
                	BaseRequest request = (BaseRequest) argument;
            		Subject currentUser = SecurityUtils.getSubject();
            		if (request != null || currentUser != null) {
            			Serializable shiroSessionId = currentUser.getSession().getId();
            			request.setLogId((String)shiroSessionId);
            			MDC.put(Constants.LOG_ID, ((BaseRequest) argument).getLogId() + "");
            		} 
                }
            }
        }
        return joinPoint.proceed();
    }
}